package org.scalpel.mainApps.HHObjects;

import java.util.concurrent.ArrayBlockingQueue;

import org.scalpel.common.HHObject;
import org.scalpel.common.KeyPoint;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;

public class DrawPath extends HHObject {
	
	static short NB_POINTS = 256;

	private double fConvPixToMeter;
	private ArrayBlockingQueue<KeyPoint> fListPoints = new ArrayBlockingQueue<KeyPoint>(NB_POINTS, true);
	private boolean fWaitForNewTarget = true;
	
	private double fDefaultPrecision = 0.3; 
	
	
	
	public DrawPath(String fName, double meterToPix) {
		super(fName);
		fConvPixToMeter = 1.0 / meterToPix;
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub

	}
	
	private void sendNewTarget(){
		KeyPoint p = null;
		synchronized(fListPoints){
			p = fListPoints.poll();
			if( p == null )
				fWaitForNewTarget = true;
			else
				fWaitForNewTarget = false;
		}
		setChanged();    
    notifyObservers(new Object[]{ "setTargetAndPrecision", new Object[]{p,fDefaultPrecision}});
	}
	
	public void isTargetReached( boolean targetReached ){
		if( targetReached)
		{
			// Send the next target
			sendNewTarget();
		}
	}
	
  /**
   * Call by the onTouch callback of the view.
   */
  public boolean onTouch(MotionEvent event){
  	
    double touchX = event.getX() * fConvPixToMeter;
    double touchY = event.getY() * fConvPixToMeter;
    
    synchronized(fListPoints){
    	fListPoints.add(new KeyPoint(touchX, touchY)); // If the queue is full this keypoint won't be added
    }
    if( fWaitForNewTarget ) 
    {
			// Send the next target
    	sendNewTarget();
    }
    return true;
  }

  /**
   * draw the robot and debug string to the main canvas
   * @param canvas reference to the main canvas
   * @param robotPaint current robotPaint
   */
  public void onDraw(Canvas canvas, Paint robotPaint){

    ///////////// Draw string info and the target ///////////// 
    canvas.save();     //================>
    
    robotPaint.setStyle(Paint.Style.STROKE);
    robotPaint.setColor(Color.BLUE);
		synchronized(fListPoints){
	    for( KeyPoint p:fListPoints){
	      canvas.drawCircle((float)(p.x/fConvPixToMeter), (float)(p.y/fConvPixToMeter), (float) (fDefaultPrecision /fConvPixToMeter), robotPaint);
	    }
		}
    robotPaint.setStyle(Paint.Style.FILL);
    canvas.restore(); //<================
    
  }
  
}
